<template>
    <div class="system-common-container">
<!--        <div class="system-common-container layout-pd">-->
        <el-card shadow="hover">
            <el-form :model="state.queryParams" ref="queryForm" :inline="true">
                <el-form-item :label-width='70' label="商户名称">
                    <el-select :clearable='true' class='ml10' v-model="state.queryParams.merchantId"
                               placeholder="请选择" filterable>
                        <el-option v-for='item in state.merchantDict' :key='item.value' :label='item.label'
                                   :value='item.value'/>
                    </el-select>
                </el-form-item>
                <el-form-item :label-width='70' label="渠道名称">
                    <el-select :clearable='true' multiple collapse-tags class='ml10'
                               v-model="state.queryParams.channelId" placeholder="请选择" filterable>
                        <el-option v-for='item in state.channelDict' :key='item.value' :label='item.label'
                                   :value='item.value'/>
                    </el-select>
                </el-form-item>
                <el-form-item :label-width='70' label="产品名称" prop="productName">
                    <el-input class='ml10' placeholder="产品名称" clearable @keyup.enter="handleQuery"
                              v-model="state.queryParams.productName"/>
                </el-form-item>
                <el-form-item :label-width='70' label='产品分类'>
                    <el-select @clear="cooperationHandleClear" :clearable='true' class='ml10'
                               v-model='state.queryParams.cooperationType' placeholder='请选择'>
                        <el-option v-for='item in optionDict.cooperationTypeDict' :key='item.value' :label='item.label'
                                   :value='item.value'/>
                    </el-select>
                </el-form-item>
                <el-form-item :label-width='70' label='日期'>
                    <el-date-picker class='ml10' v-model='state.queryParams.dateRange' type='daterange'
                                    inputmode="none"
                                    :shortcuts="selectShortcuts"
                                    placeholder='日期'
                                    date-format="YYYY/MM/DD" value-format="YYYY-MM-DD"
                                    :disabled-date="disableFutureDates"
                                    range-separator='至' start-placeholder='开始日期' end-placeholder='结束日期'
                                    :picker-options="{firstDayOfWeek: 1 }"
                                    :clearable="false"
                    />
                </el-form-item>
                <el-form-item>
                    <el-button-group>
                        <el-button type="primary" icon="ele-Search" @click="handleQuery" :loading="state.loading"
                                   v-auth="'esSettlementBill:query'"> 查询
                        </el-button>
                        <el-button icon="ele-Refresh" @click="resetQuery" v-auth="'esSettlementBill:query'"> 重置
                        </el-button>
                    </el-button-group>
                    <el-button icon="ele-FolderOpened" type="success" plain @click="exportCommonSettlementExcel"
                               v-auth="'esSettlementBill:query'" :loading="state.loading"> 导出
                    </el-button>
                    <el-button icon="ele-FolderOpened" type="warning" plain @click="exportChannelExcel"
                               v-auth="'esSettlementBill:query'" :loading="state.loading"> 渠道导出
                    </el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <el-card shadow='hover' style='margin-top: 8px;'>
            <div style="margin: -18px 0 20px 0;">
                <el-pagination @size-change="onHandleSizeChange" @current-change="onHandleCurrentChange" class="mt15"
                               :page-sizes="[10, 50, 100]" v-model:current-page="state.queryParams.pageNum" background
                               v-model:page-size="state.queryParams.pageSize"
                               layout="total, sizes, prev, pager, next, jumper"
                               :total="state.total"/>
            </div>
            <el-table max-height="1000px" :data='state.data' stripe highlight-current-row border show-summary
                      v-loading="state.loading" :summary-method="getSummaries">
                <el-table-column header-align="center" prop="byYmd" label="日期" align="center" width="100"
                                 show-overflow-tooltip/>
                <el-table-column header-align="center" prop="productName" label="产品名称" align="left" min-width="420"
                                 show-overflow-tooltip/>
                <el-table-column header-align="center" label="产品分类" align="center" min-width="120"
                                 show-overflow-tooltip>
                    <template #default="scope">
                        <el-tag v-if="scope.row.cooperationType === 1">官方报备</el-tag>
                        <el-tag type="success" v-else-if="scope.row.cooperationType === 2">包的业务</el-tag>
                        <el-tag type="warning" v-else-if="scope.row.cooperationType === 3">三方业务</el-tag>
                    </template>
                </el-table-column>
                <el-table-column header-align="center" label="产品部分" align="left" min-width="120"
                                 show-overflow-tooltip>
                    <el-table-column header-align="center" prop="informationFee" label="信息费(元)" align="right"
                                     min-width="120" show-overflow-tooltip>
                        <template #default="scope">
                            {{ (scope.row.informationFee / 1.00).toFixed(2) }}
                        </template>
                    </el-table-column>
                    <el-table-column header-align="center" prop="informationFeeCount" label="订购成功数" align="right"
                                     min-width="120" show-overflow-tooltip/>
                    <el-table-column header-align="center" prop="informationFeeSubTotal" label="产品小计(元)"
                                     align="right" min-width="120" show-overflow-tooltip>
                        <template #default="scope">
                            {{ (scope.row.informationFeeSubTotal / 1.00).toFixed(2) }}
                        </template>
                    </el-table-column>
                </el-table-column>
                <el-table-column header-align="center" label="商户部分" align="left" min-width="120"
                                 show-overflow-tooltip>
                    <el-table-column header-align="center" prop="merchantName" label="商户名称" align="left"
                                     min-width="120" show-overflow-tooltip/>
                    <el-table-column header-align="center" prop="merchantSettlementPrice" label="结算价格(元)"
                                     align="right" min-width="130" show-overflow-tooltip>
                        <template #default="scope">
                            {{ (scope.row.merchantSettlementPrice / 1.00).toFixed(2) }}
                        </template>
                    </el-table-column>
                    <el-table-column header-align="center" prop="merchantOrderCount" label="订购成功数" align="right"
                                     min-width="130" show-overflow-tooltip/>
                    <el-table-column header-align="center" prop="merchantSettlementSubTotal" label="商户小计(元)"
                                     align="right" min-width="140" show-overflow-tooltip>
                        <template #default="scope">
                            {{ (scope.row.merchantSettlementSubTotal / 1.00).toFixed(2) }}
                        </template>
                    </el-table-column>
                </el-table-column>
                <el-table-column header-align="center" label="商务利润" align="left" min-width="120"
                                 show-overflow-tooltip>
                    <el-table-column header-align="center" prop="profitPrice" label="价格利润(元)" align="right"
                                     min-width="130" show-overflow-tooltip>
                        <template #default="scope">
                            {{ (scope.row.profitPrice / 1.00).toFixed(2) }}
                        </template>
                    </el-table-column>
                    <el-table-column header-align="center" prop="deductionOrderCount" label="扣量数" align="right"
                                     min-width="130" show-overflow-tooltip/>
                    <el-table-column header-align="center" prop="profitPriceSubTotal" label="利润小计(元)" align="right"
                                     min-width="140" show-overflow-tooltip>
                        <template #default="scope">
                            {{ (scope.row.profitPriceSubTotal / 1.00).toFixed(2) }}
                        </template>
                    </el-table-column>
                </el-table-column>
                <!-- <el-table-column header-align="center" prop="refundTotal" label="退费数量" align="center" min-width="100" show-overflow-tooltip />-->
                <el-table-column header-align="center" label="渠道部分" align="left" min-width="120"
                                 show-overflow-tooltip>
                    <el-table-column header-align="center" prop="channelName" label="渠道名称" align="left"
                                     min-width="120" show-overflow-tooltip/>
                    <el-table-column header-align="center" prop="channelSettlementPrice" label="结算价格(元)"
                                     align="right" min-width="130" show-overflow-tooltip>
                        <template #default="scope">
                            {{ (scope.row.channelSettlementPrice / 1.00).toFixed(2) }}
                        </template>
                    </el-table-column>
                    <el-table-column header-align="center" prop="channelOrderCount" label="订购成功数" align="right"
                                     min-width="130" show-overflow-tooltip/>
                    <el-table-column header-align="center" prop="channelSettlementSubTotal" label="渠道小计(元)"
                                     align="right" min-width="140" show-overflow-tooltip>
                        <template #default="scope">
                            {{ (scope.row.channelSettlementSubTotal / 1.00).toFixed(2) }}
                        </template>
                    </el-table-column>
                </el-table-column>
            </el-table>
            <el-pagination @size-change="onHandleSizeChange" @current-change="onHandleCurrentChange" class="mt15"
                           :page-sizes="[10, 50, 100]" v-model:current-page="state.queryParams.pageNum" background
                           v-model:page-size="state.queryParams.pageSize"
                           layout="total, sizes, prev, pager, next, jumper"
                           :total="state.total"/>
        </el-card>
    </div>
</template>

<script setup lang="ts" name="esCommonSettlementBill">

import {reactive, onMounted} from 'vue';
import {ElMessage} from 'element-plus';
import {getFileName, downloadByData} from '/@/utils/download';
import {selectShortcuts, disableFutureDates, todayDate} from '/@/utils/dateHelper';

import SysEsSettlementBillApi from '/@/api/exocytosis/settlement';
import SysEsMerchantApi from '/@/api/exocytosis/merchant';
import SysEsChannelApi from '/@/api/exocytosis/channel';
import {optionDict} from "/@/const/dict";
import {sysBaseDict} from "/@/api/models";

// 定义变量内容
const state = reactive({
    loading: false,
    data: [],
    total: 0 as any,
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        productName: undefined,
        dateRange: [todayDate(), todayDate()],
        merchantId: undefined,
        channelId: [],
        cooperationType: undefined,
    },
    statisticsData: {
        informationFeeSubCountSun: 0,
        informationFeeSubTotalSun: 0,
        merchantOrderCountSun: 0,
        merchantSettlementSubTotalSun: 0,
        channelOrderCountSun: 0,
        channelSettlementSubTotalSun: 0,
        businessPriceementSubTotalSun: 0,
    },
    merchantDict: [] as sysBaseDict[],
    channelDict: [] as sysBaseDict[],
});

// 页面加载时
onMounted(async () => {
    await merchantDictQuery();
    await channelDictQuery();
});

// 查询操作
const handleQuery = async () => {
    // 1. 验证日期范围
    if (state.queryParams.dateRange.length === 0) {
        return ElMessage.warning('请先选择日期');
    }

    try {
        state.loading = true;

        // 2. 参数处理（自动过滤空值）
        const params = {
            ...state.queryParams,
            // operatorPlatform: state.queryParams.operatorPlatform || undefined // 自动转换空字符串
        };

        // 3. API请求
        const {data} = await SysEsSettlementBillApi().queryCommonSettlementRecord(params);

        // 4. 响应处理（安全取值）
        state.data = data?.result?.items || [];
        state.total = data?.result?.total || 0;
        state.statisticsData = data?.result?.statisticsData;

    } catch (error) {
        ElMessage.error('数据加载失败');
    } finally {
        state.loading = false;
    }
};

// 重置操作
const resetQuery = () => {
    // 1. 批量重置为undefined
    const keepKeys: string[] = ['pageNum', 'pageSize', 'dateRange', 'channelId']; // 声明需要保留的字段
    Object.keys(state.queryParams).forEach(key => {
        if (!keepKeys.includes(key))
            state.queryParams[key] = undefined;
    });
    // 2. 单独处理日期
    state.queryParams.dateRange = [todayDate(), todayDate()];
    state.queryParams.channelId = [];
    state.data = [];
};

const exportCommonSettlementExcel = async () => {
    state.loading = true;
    SysEsSettlementBillApi().exportCommonSettlementExcel(state.queryParams).then((res) => {
        const fileName = getFileName(res.headers);
        downloadByData(res.data as any, fileName);
        state.loading = false;
    });
};

const exportChannelExcel = async () => {
    state.loading = true;
    SysEsSettlementBillApi().exportChannelExcel(state.queryParams).then((res) => {
        const fileName = getFileName(res.headers);
        downloadByData(res.data as any, fileName);
        state.loading = false;
    });
};

// 改变页面容量
const onHandleSizeChange = (val: number) => {
    state.queryParams.pageSize = val;
    handleQuery();
};

// 产品分类状态清空
const cooperationHandleClear = () => {
    state.queryParams.cooperationType = undefined
};

// 改变页码序号
const onHandleCurrentChange = (val: number) => {
    state.queryParams.pageNum = val;
    handleQuery();
};

// 商户列表
const merchantDictQuery = async () => {
    await SysEsMerchantApi().queryAll().then((res) => {
        if (res.data.resCode === '0000')
            state.merchantDict = res.data.result ?? [];
    });
};

// 渠道列表
const channelDictQuery = async () => {
    await SysEsChannelApi().queryAll().then((res) => {
        if (res.data.resCode === '0000')
            state.channelDict = res.data.result ?? [];
    });
};

const getSummaries = (param) => {
    //table自定义合计行方法summary-method
    const {columns, data} = param
    const sums = []
    columns.forEach((column, index) => {
        if (index === 0) {
            sums[index] = '合计（元）';
            return
        }
        if (index === 4) {
            sums[4] = state.statisticsData.informationFeeSubCountSun;
            return
        }

        if (index === 5) {
            sums[5] = state.statisticsData.informationFeeSubTotalSun;
            sums[5] = (sums[5] / 1.00).toFixed(2);
            return
        }
        if (index === 8) {
            sums[8] = state.statisticsData.merchantOrderCountSun;
            return
            // const values = data.map(item => Number(item[column.property]))
            // sums[4] = values.reduce((prev, curr) => {
            // 	return prev + curr
            // }, 0)
        }
        if (index === 9) {
            sums[9] = state.statisticsData.merchantSettlementSubTotalSun;
            // const values = data.map(item => Number(item[column.property]))
            // sums[5] = values.reduce((prev, curr) => {
            // 	return prev + curr
            // }, 0)
            sums[9] = (sums[9] / 1.00).toFixed(2);
            return
        }
        if (index === 11) {
            sums[11] = state.statisticsData.deductionOrderCountSun;
            return
            // const values = data.map(item => Number(item[column.property]))
            // sums[4] = values.reduce((prev, curr) => {
            // 	return prev + curr
            // }, 0)
        }
        if (index === 12) {
            sums[12] = state.statisticsData.profitPriceSettlementSubTotalSun;
            // const values = data.map(item => Number(item[column.property]))
            // sums[5] = values.reduce((prev, curr) => {
            // 	return prev + curr
            // }, 0)
            sums[12] = (sums[12] / 1.00).toFixed(2);
            return
        }
        // if(index === 13){
        //   sums[13] = state.statisticsData.refundCountSun;
        //   return
        // }
        if (index === 15) {
            sums[15] = state.statisticsData.channelOrderCountSun;
            return
            // const values = data.map(item => Number(item[column.property]))
            // sums[8] = values.reduce((prev, curr) => {
            //   return prev + curr
            // }, 0)
        }
        if (index === 16) {
            sums[16] = state.statisticsData.channelSettlementSubTotalSun;
            // const values = data.map(item => Number(item[column.property]))
            // sums[9] = values.reduce((prev, curr) => {
            // 	return prev + curr
            // }, 0)
            sums[16] = (sums[16] / 1.00).toFixed(2);
            return
        }
    })
    return sums
}
</script>
